package com.leetcode.题库;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 覃国强
 * @date 2022-02-20 16:40
 */
public class 题库_0003_无重复字符的最长子串 {


  public static void main(String[] args) {
    Solution solution = new Solution();
    String s = "abba";
    int length = solution.lengthOfLongestSubstring(s);
    System.out.println(length);
  }


  static
  class Solution {
    public int lengthOfLongestSubstring(String s) {
      if (s == null || s.length() < 2) {
        return s == null ? 0 : s.length();
      }

      int leftIndex = 0;
      int rightIndex = 1;

      char[] chars = s.toCharArray();
      Map<Character, Integer> map = new HashMap<>();
      map.put(chars[0], 0);
      int result = 0;

      for (; rightIndex < chars.length; ++rightIndex) {
        if (map.containsKey(chars[rightIndex])) {
          // 计算上一个子串的长度
          result = Math.max(result, rightIndex - leftIndex);
          if (leftIndex <= map.get(chars[rightIndex])) {
            leftIndex = map.get(chars[rightIndex]) + 1;
          }
        }
        map.put(chars[rightIndex], rightIndex);
      }
      result = Math.max(result, rightIndex - leftIndex);

      return result;
    }
  }

}
